const models = require("../db/mysqldb/index");
const { fail, success, CODE, getClientIp } = require("../utils/utils");
const svgCaptcha = require("svg-captcha");
const { setDataToCache } = require("../utils/nodeCache");
const logger = require("../utils/logger");

class SystemController {
  static async init(ctx) {
    try {
      await models.sequelize.sync({});
      return ctx.body = success(null, `mysql table create success`, CODE.SUCCESS);
    } catch (error) {
      return ctx.body = fail(
        null,
        `错误信息：${error.message}`,
        CODE.SYSTEM_INIT_ERROR
      );
    }
  }
  /**
   * @description 获取验证码
   * @param {*} ctx
   */
  static async getCode(ctx, next) {
    const codeConfig = {
      size: 2,
      ignoreChars: "0o1i",
      noise: 1,
      color: true,
      // 宽度
      width: 100,
      // 高度
      height: 34,
      background: "#cc9966",
    };
    let captcha = svgCaptcha.createMathExpr(codeConfig);
    await setDataToCache("captcha-" + getClientIp(ctx.req), captcha.text);
    logger.logHandle(captcha);
    return (ctx.body = success(
      { text: captcha.text, result: captcha.data },
      "",
      CODE.SUCCESS
    ));
  }
}

module.exports = {
  SystemController,
};
